﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;

namespace Frame
{
    public class ScreenHelper
    {

        [DllImport("user32.dll")]
        static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, uint uFlags);
        /// <summary>
        /// 设置要显示到的显示器
        /// </summary>
        /// <param name="frm">窗口对象</param>
        /// <param name="index">显示器编号 0：第一块 1：第二块</param>
        /// <param name="topMost">true：置顶 false：取消置顶</param>
        public static void ShowScreen(Form frm, bool topMost, int index = -1)
        {
            FormWindowState state = frm.WindowState;
            frm.WindowState = FormWindowState.Normal;
            Screen[] screens = Screen.AllScreens;
            if (index == -1) index = ScreenIndex;
            if (screens.Length > index)
            {
                // 获取第二个屏幕的工作区域（不包括任务栏）
                Rectangle secondScreenBounds = screens[index].WorkingArea;

                // 设置应用程序的窗口位置和大小
                frm.Left = secondScreenBounds.Left;
                frm.Top = secondScreenBounds.Top;
                frm.Width = secondScreenBounds.Width;
                frm.Height = secondScreenBounds.Height;
                frm.WindowState = state;
                frm.TopMost = topMost;
            }
        }

        public static void ShowScreen(Form frm, int index = -1)
        {
            Screen[] screens = Screen.AllScreens;
            if (index == -1) index = ScreenIndex;
            if (screens.Length > index)
            {
                // 获取第二个屏幕的工作区域（不包括任务栏）
                Screen screen = Screen.AllScreens[index];
                // 计算窗口在屏幕中间的位置


                // 设置窗口的位置和大小
                frm.StartPosition = FormStartPosition.Manual;
                int x = screen.WorkingArea.Left + screen.WorkingArea.Width / 2 - frm.Width / 2;
                int y = screen.WorkingArea.Top + screen.WorkingArea.Height / 2 - frm.Height / 2;
                frm.Location = new Point(x, y);
            }
        }
        /// <summary>
        /// 获取屏幕数量
        /// </summary>
        /// <returns></returns>
        public static int GetScreenNumber()
        {
            return Screen.AllScreens.Count();
        }
        private static string m_IniParam = System.Windows.Forms.Application.StartupPath + @"\PARAM\MainParam.ini";
        private static int ScreenIndex = 0;
        public static void LoadParam()
        {
            string Screens = IniFileHelper.GetValue("Main", "Screen", m_IniParam);
            ScreenIndex = Convert.ToInt32(Screens == "ERROR" ? "0" : Screens);
        }


    }
}
